<template>
  <div class="swiper-container">
    <div class="header">
      <h2>轮播图管理</h2>
      <el-button type="primary" @click="dialogVisible = true">添加轮播图</el-button>
    </div>

    <!-- 轮播图列表 -->
    <el-table 
      :data="paginatedSwiperList" 
      style="width: 100%" 
      v-loading="loading"
      max-height="600"
      :scrollbar-always-on="true">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="轮播图">
        <template #default="scope">
          <el-image 
            style="width: 100px; height: 60px" 
            :src="scope.row.imgUrl" 
            :preview-src-list="[scope.row.imgUrl]"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="imgUrl" label="图片地址" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.state === 1 ? 'success' : 'danger'">
            {{ scope.row.state === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加轮播图对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加轮播图"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="图片地址" prop="imgSrc">
          <el-input v-model="form.imgSrc" placeholder="请输入轮播图片URL地址"></el-input>
        </el-form-item>
        <el-form-item label="图片预览">
          <el-image 
            v-if="form.imgSrc" 
            style="width: 300px; height: 180px" 
            :src="form.imgSrc" 
            fit="cover"
          />
          <div v-else class="empty-preview">
            输入URL后显示预览
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted,computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllSwiper, addSwiper, delSwiper } from '../../api/swiper'

// 数据
const swiperList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分页后的轮播图列表
const paginatedSwiperList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return swiperList.value.slice(start, end)
})

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

// 表单数据
const form = ref({
  imgSrc: ''
})

// 表单验证规则
const rules = {
  imgSrc: [
    { required: true, message: '请输入轮播图片URL地址', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
  ]
}

// 获取轮播图列表
const fetchSwiperList = async () => {
  loading.value = true
  try {
    const res = await getAllSwiper()
    if (res.status === 0) {
      swiperList.value = res.data
      // 更新总数
      total.value = swiperList.value.length
      // 重置到第一页
      currentPage.value = 1
    } else {
      ElMessage.error(res.message || '获取轮播图列表失败')
    }
  } catch (error) {
    console.error('获取轮播图列表出错:', error)
    ElMessage.error('获取轮播图列表失败')
  } finally {
    loading.value = false
  }
}

// 添加轮播图
const handleAdd = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const res = await addSwiper(form.value)
        if (res.status === 0) {
          ElMessage.success('添加轮播图成功')
          dialogVisible.value = false
          form.value.imgSrc = ''
          fetchSwiperList()
        } else {
          ElMessage.error(res.message || '添加轮播图失败')
        }
      } catch (error) {
        console.error('添加轮播图出错:', error)
        ElMessage.error('添加轮播图失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除轮播图
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这张轮播图吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await delSwiper({ id: row.id })
      if (res.status === 0) {
        ElMessage.success('删除轮播图成功')
        fetchSwiperList()
      } else {
        ElMessage.error(res.message || '删除轮播图失败')
      }
    } catch (error) {
      console.error('删除轮播图出错:', error)
      ElMessage.error('删除轮播图失败')
    }
  }).catch(() => {
    // 取消删除操作
  })
}

// 页面加载时获取轮播图列表
onMounted(() => {
  fetchSwiperList()
})
</script>

<style scoped>
.swiper-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.empty-preview {
  width: 300px;
  height: 180px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  border: 1px dashed #d9d9d9;
}

.pagination-container {
  margin-top: 20px;
  padding: 10px 0;
  display: flex;
  justify-content: flex-end;
}
</style>